using UnityEngine;
using QFramework;
using ProjectSurvivor;
using QAssetBundle;

namespace QFrameworkSurvivor
{
    public partial class Ball : ViewController
    {
        void Start()
        {
            // Code Here
            Global.SuperBasketBall.RegisterWithInitValue(unlocked =>
            {
                if (unlocked)
                {
                    this.LocalScale(3);
                }
            });

            SelfRigidbody2D.velocity = new Vector2(x: Random.Range(-1.0f, 1.0f), y: Random.Range(-1.0f, 1.0f) *
                                       Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2));

            HurtBox.OnTriggerEnter2DEvent(collider =>
            {
                var hurtBox = collider.GetComponent<HitHurtBox>();
                if (hurtBox)
                {
                    if (hurtBox.Owner.CompareTag("Enemy") && hurtBox.gameObject)
                    {

                        var damageTimes = Global.SuperBasketBall.Value ? Random.Range(2, 3 + 1) : 1;
                        DamageSystem.CalculateDamage(Global.BasketBallDamage.Value, hurtBox.Owner.GetComponent<IEnemy>());
                    }
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }
        private void OnCollisionEnter2D(Collision2D other)
        {
            var normal = other.GetContact(index: 0).normal;
            if (normal.x > normal.y)
            {
                SelfRigidbody2D.velocity = new Vector2(SelfRigidbody2D.velocity.x,
                y: Mathf.Sign(SelfRigidbody2D.velocity.y) * Random.Range(0.5f, 1.5f) *
                Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2));
                SelfRigidbody2D.angularVelocity = Random.Range(-360, 360);
            }
            else
            {
                var rb = SelfRigidbody2D;
                rb.velocity =
                new Vector2(Mathf.Sign(rb.velocity.x) * Random.Range(0.5f, 1.5f) * Random.Range(Global.BasketBallSpeed.Value - 2,
                Global.BasketBallSpeed.Value + 2),
                rb.velocity.y);
                rb.angularVelocity = Random.Range(-360f, 360f);
            }
            AudioKit.PlaySound(Sfx.BALL);
        }
    }
}
